<template>
  <van-list
    v-model="loading"
    :finished="finished"
    finished-text="没有更多了"
    :error.sync="error"
    error-text="请求失败，点击重新加载"
    @load="onLoad"
    >
  <commentItem v-for="(obj, index) in list" :key="index" :comment="obj" @replyComment="$emit('replyComment', $event)" ></commentItem>
</van-list>
</template>
<script>
// 导入文章评论项
import commentItem from '@/components/commentItem'
// 获取文章评论接口
import { getCommentList } from '@/api/comment'
export default {
  data () {
    return {
      loading: false,
      finished: false,
      offset: null, // 获取评论列表偏移量
      limit: 10, // 每次获取评论数
      error: false // list组件获取数据错误提示
    }
  },
  props: {
    list: {
      type: Array,
      default: () => []
    },
    type: {
      type: String,
      validator (value) {
        return ['a', 'c'].includes(value)
      },
      default: 'a'
    },
    artID: {
      type: [String, Number, Object]
    }
  },
  inject: {
    articleID: {
      type: [String, Number, Object]
    }
  },
  created () {
    // 解决页面刷新的时候加载没有加载状态
    this.loading = true
    this.onLoad()
  },
  methods: {
    async onLoad () {
      // 1获取数据
      try {
        const { data } = await getCommentList({
          type: this.type,
          source: this.artID || this.articleID,
          offset: this.offset,
          limit: this.limit
        })
        // 2将数据的值给list
        this.list.push(...data.data.results)
        // 3加载状态结束
        this.loading = false
        // 4判断数据是否已全部加载
        if (data.data.results.length) {
          this.offset = data.data.last_id
        } else {
          this.finished = true
        }
        this.$emit('commentCount', data.data.total_count)
      } catch (err) {
        this.error = true
        this.loading = false
        this.$toast('获取失败，请重试')
      }
    }
  },
  components: {
    commentItem
  }
}
</script>

<style>

</style>
